/**
 * Created by Administrator on 2016/2/18.
 */
$(function () {
    function renderTable(data, type) {

        if (!data || !data.header.length) {
            //未返回数据或者表头数据为空，无法渲染
            return false;
        }
        var $table = $("#activityTable");
        var dataSize = data.header.length;
        var html = [];
        html.push('<tr><td><input name="allRatio" type="checkbox"/></td>');
        html.push("<td>序号</td>");
        for (var i = 0; i < data.header.length; i++) {
            html.push("<th>" + getTableHeaderItem(data.header[i]) + "</th>");
        }
        html.push("</tr>");
        if (!data.userlist) {
            //没有报名数据可以加载
            $table.html(html.join(""));
            if (type = "selected") {
                //查看已选名单
                var tpl_noSelectedUserView = _.template($("#tpl_noSelectedUserView"));
                $table.append(tpl_noSelectedUserView());
            } else if (type = "all") {

            }
            return true;
        }
        for (var n = 0; n < data.userlist.length; n++) {
            html.push('<tr><td><input name="userRatio' + n + '" type="checkbox" atvId="' + data.userlist[n][0] + '" ' + (!(data.userlist[n][1]) ? '' : 'checked="checked" disabled ') + ' />');
            html.push('</td><td>' + n + '</td>>');

            for (var m = 0; m < dataSize; m++) {
                html.push("<td>" + data.userlist[n][m + 2] + "</td>");
            }
            html.push("</tr>");
        }
        $table.html(html.join(""));

        return true;
    }

    function init() {
        if (config.debug) {
            renderTable(localJson.activityTableData);
        } else {
            var data = {
                atvId: config.manageActivity.atvId,
                selectMode: "allmode",//全选
            }
            getTableData(data);
        }
    }

    init();

    function getTableHeaderItem(item) {
        if (!item) {
            return "";
        }
        if (item.type == "normal") {
            //文本选项
            return item.name;
        }
        if (item.type == "selectOne") {
            var html = [];
            html.push('<select><option value="1">' + item.name + '</option>');
            _.each(item.option, function (index, i) {
                html.push('<option value="' + i + '">' + index + '</option>');
            });
            html.push('</select>');
            return html.join("");
        }
    }

    function getTableData(data) {
        $.ajax({
            url: CK.formatUrl(config.service.getSignUpUserList),
            data: {
                atvId: data.atvId,
                selectMode: data.selectMode,
                pageSize: data.pageSize,
                pageNum: data.pageNum,
                filtercdn: data.filtercdn,
                ordercdn: data.ordercdn
            },
            type: "POST",
            async: "true",
            success: function (response) {
                if (response.code != AjaxCode.success) {
                    CK.alert(response.msg);
                    return;
                }
                renderTable(response.data);
            },
            error: function () {

            }
        });
    }

    function ifEnableAddBtn() {
        var checkedList = $("#activityTable")
            .find("input[type=checkbox]:not(:disabled)[name^='userRatio']:checked");
        if (checkedList.length == 0) {
            $("#addToChooseList").attr("disabled", "");
        } else {
            $("#addToChooseList").removeAttr("disabled");
        }
    }

    $("#activityTable").delegate("[name=allRatio]", "click", function () {
        var $this = $(this);

        if ($this.is(":checked")) {
            //被选中了
            $("#activityTable")
                .find("input[type=checkbox]:not(:disabled)[name^='userRatio']")
                .prop('checked', true);
            ifEnableAddBtn();
        } else {
            $("#activityTable")
                .find("input[type=checkbox]:not(:disabled)[name^='userRatio']")
                .removeAttr("checked");
            $("#addToChooseList").attr("disabled", "");
        }
    });

    $("#activityTable").delegate("[name^='userRatio']", "click", function () {
        ifEnableAddBtn();
    });

    $("#addToChooseList").click(function () {
        var list = [];
        $("#activityTable")
            .find("input[type=checkbox]:not(:disabled)[name^='userRatio']").each(function () {
            var $this = $(this);
            list.push($this.attr("atvId"));
        });
        if (config.debug) {
            $("#activityTable")
                .find("input[type=checkbox]:not(:disabled)[name^='userRatio']:checked")
                .attr("disabled", "true");
            CK.alert("已添加用户到已选名单！")
        }
        $.ajax({
            url: CK.formatUrl(config.service.modifySignUpUserSelect),
            data: {
                atvid: config.manageActivity.atvid,
                ids: list,
                selectmode: true //选择用户
            },
            type: "POST",
            async: "true",
            success: function (response) {
                if (response.code != AjaxCode.success) {
                    CK.alert(response.msg);
                    return;
                }
                $("#activityTable")
                    .find("input[type=checkbox]:not(:disabled)[name^='userRatio']:checked")
                    .attr("disabled", "true");
                CK.alert("已添加用户到已选名单！")

            },
            error: function () {

            }
        });
    });

    //查看已选择名单
    $("#viewChooseList").click(function () {
        $("#viewChooseList").addClass("hidden");
        $("#addToChooseList").addClass("hidden");
        $("#goToAllList").removeClass("hidden");
        if (config.debug) {
            renderTable(localJson.activityTableDataChoosed, "selected");
            return;
        }
        $.ajax({
            url: CK.formatUrl(config.service.getSignUpUserList),
            data: {
                atvId: config.manageActivity.atvId,
                selectMode: "selectedMode" //选择用户
            },
            type: "POST",
            async: "true",
            success: function (response) {
                if (response.code != AjaxCode.success) {
                    CK.alert(response.msg);
                    return;
                }
                renderTable(response.data.userList, "selected");

            },
            error: function () {

            }
        });
    });


    //返回全部名单
    $("#goToAllList").click(function () {
        $("#goToAllList").addClass("hidden");
        $("#viewChooseList").removeClass("hidden");
        $("#addToChooseList").removeClass("hidden");
        init();
    });

});
